<template>
  <div class="prod-detail">
    <CateHea class="prod-detail-hea">
      <template #left><i class="iconfont icon-zuojiantou" @click="$router.go(-1)"></i></template>
      <template #center>
        <div class="nav-list">
          <span @click="navActive(0)"><i :class="{ iconfont: true, 'icon-shouye1': navIndex == 0 }"></i>商品</span>
          <span @click="navActive(1)"><i :class="{ iconfont: true, 'icon-shouye1': navIndex == 1 }"></i>商品详情</span>
          <span @click="navActive(2)"><i :class="{ iconfont: true, 'icon-shouye1': navIndex == 2 }"></i>商品推荐</span>
        </div>
      </template>
      <template #right><i class="iconfont icon-shixincaidan"></i></template>
    </CateHea>
    <section class="prod-focus">
      <Slide :hea-slide="heaSlide"></Slide>
      <div class="detail-info">
        <p class="detail-info-name">{{ productDetail.name }}</p>
        <p class="detail-info-subtitle">{{ productDetail.subscribe }}</p>
        <div>
          <span class="detail-info-price">￥{{ productDetail.price }}</span>
          <span class="detail-info-stock">库存{{ productDetail.stock }}件</span>
        </div>
      </div>
      <div class="detail-content" ref="detailContent" id="content">
        <p class="detail-gap"></p>
        <ul>
          <li>概述</li>
          <li>参数</li>
          <li>安装服务</li>
          <li>常见问题</li>
        </ul>
        <div class="info" v-html="productDetail.detail"></div>
      </div>
    </section>
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon icon="cart-o" text="购物车" :info="$store.getters.getBadgeCount" @click="$router.push('/shopcart')" />
      <van-goods-action-button type="warning" text="加入购物车" @click="addToCar" />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
    <van-sku
      v-model="show"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      :hide-stock="sku.hide_stock"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
      @stepper-change="onStepperChange"
    />
  </div>
</template>

<script>
import CateHea from '@/components/common/CateHea'
import Slide from '@/components/common/Slide'
import { getDetailInfo, addSingleShopCar } from '@/http/index.js'
export default {
  data() {
    return {
      id: this.$route.params.id,
      goodsId: this.$route.params.id,
      count: 1,
      navIndex: 0,
      productDetail: {}, // 保存详情数据
      heaSlide: [],
      show: false,
      sku: {
        tree: [
          {
            k: '颜色', // skuKeyName：规格类目名称
            v: [
              {
                id: '001', // skuValueId：规格值 id
                name: '红色', // skuValueName：规格值名称
                imgUrl: 'http://img.happymmall.com/570186f3-c0d2-4336-a1b7-3e1aff88f73a.jpg', // 规格类目图片，只有第一个规格类目可以定义图片
                previewImgUrl: 'http://img.happymmall.com/570186f3-c0d2-4336-a1b7-3e1aff88f73a.jpg', // 用于预览显示的规格类目图片
              },
              {
                id: '002',
                name: '蓝色',
                imgUrl: 'http://img.happymmall.com/a73b6326-1204-4937-aa88-097c9eda8a2a.jpg',
                previewImgUrl: 'http://img.happymmall.com/a73b6326-1204-4937-aa88-097c9eda8a2a.jpg',
              },
            ],
            k_s: 's1', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
          },
        ],
        list: [
          {
            id: 2259, // skuId，下单时后端需要
            price: 100, // 价格（单位分）
            s1: '001', // 规格类目 k_s 为 s1 的对应规格值 id
            stock_num: 50, // 当前 sku 组合对应的库存
          },
          {
            id: 2259, // skuId，下单时后端需要
            price: 100, // 价格（单位分）
            s1: '002', // 规格类目 k_s 为 s1 的对应规格值 id
            stock_num: 50, // 当前 sku 组合对应的库存
          },
        ],
        price: '100', // 默认价格（单位元）
        stock_num: 100, // 商品总库存
        collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
      },
      // 商品配置
      goods: {
        // 商品标题
        title: '测试商品',
        // 默认商品 sku 缩略图
        picture: 'http://img.happymmall.com/570186f3-c0d2-4336-a1b7-3e1aff88f73a.jpg',
      },
    }
  },
  components: {
    CateHea,
    Slide,
  },
  created() {
    this.fetchSlide()
  },
  methods: {
    fetchSlide() {
      getDetailInfo({ params: { id: this.id } }).then((res) => {
        this.productDetail = res.data
        // console.log(this.productDetail)
        // console.log(this.productDetail.subImages)
        if (this.productDetail.subImages) {
          let subImages = this.productDetail.subImages.split(',')
          let imageHost = this.productDetail.imageHost
          subImages.forEach((item) => {
            this.heaSlide.push({
              imgUrl: imageHost + item,
            })
          })
          this.setSku(this.productDetail, this.heaSlide)
        }
      })
      //#region
      // this.$http.get('/api/product/detail', { params: { id: this.id } }).then((res) => {
      //   const { data } = res
      //   this.productDetail = data.data
      //   console.log(this.productDetail)
      //   let subImages = this.productDetail.subImages.split(',')
      //   let imageHost = this.productDetail.imgHost
      //   subImages.forEach((item) => {
      //     this.heaSlide.push({
      //       imgUrl: imageHost + item,
      //     })
      //   })
      // })
      //#endregion
    },
    navActive(index) {
      // console.log(index)
      this.navIndex = index
      switch (index) {
        case 0:
          window.scroll(0, 0)
          break
        case 1:
          // console.log(this.$refs.detailContent.offsetTop)
          window.scroll(0, this.$refs.detailContent.offsetTop - 50)
          break
        default:
          break
      }
    },
    onBuyClicked() {},
    onAddCartClicked() {
      addSingleShopCar({ productId: this.goodsId, count: this.count }).then((res) => {
        if (res.status == 0) {
          this.$toast('添加成功')
          this.$store.dispatch('getCarDataList')
          this.show = false
        }
      })
    },
    onStepperChange(val) {
      this.count = val
    },
    setSku(detailInfo, tempList) {
      // console.log(tempList)
      let tempTreeV = []
      this.sku.list = []
      for (let index = 0; index < tempList.length; index++) {
        // 组装 suk.tree[0].v
        let obj = {
          id: index + 1, // skuValueId：规格值 id
          name: '红色', // skuValueName：规格值名称
          imgUrl: tempList[index].imgUrl, // 规格类目图片，只有第一个规格类目可以定义图片
          previewImgUrl: tempList[index].imgUrl, // 用于预览显示的规格类目图片
        }
        if (index === 1) {
          obj.name = '蓝色'
        } else if (index === 2) {
          obj.name = '绿色'
        } else if (index == 3) {
          obj.name = '黑色'
        }
        tempTreeV.push(obj)
        // 组装 sku.list
        let preItem = {
          id: detailInfo.id, // skuId
          s1: index + 1, // 规格类目 k_s 为 s1 的对应规格值 id
          price: detailInfo.price * 100, // 价格（单位分）
          stock_num: detailInfo.stock - 1, // 当前 sku 组合对应的库存
        }
        if (index === 1) {
          preItem.stock_num = 1
        }
        this.sku.list.push(preItem)
      }
      this.sku.tree[0].v = tempTreeV
      // 价格 和库存总数
      this.sku.price = this.productDetail.price // 默认价格（单位元）
      this.sku.stock_num = this.productDetail.stock - 0 // 商品总库存

      // 商品展示的默认图
      this.goods.picture = tempList[0].imgUrl
      //   设置 对应商品ID
      this.goodsId = detailInfo.id
    },
    addToCar() {
      // console.log('--', typeof this.$store.getters.getIsLogin)
      if (this.$store.getters.getIsLogin == false) {
        this.$dialog
          .confirm({ closeOnClickOverlay: true, title: '提示！', message: '未登录请登录' })
          .then(() => {
            this.$router.push('/login')
          })
          .catch(() => {
            console.log('关闭')
          })
        return
      }
      this.show = true
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/mixin.scss';
.prod-detail-hea {
  background-color: white;
  .nav-list {
    width: 100%;
    span {
      margin: 0 20px;
    }
    i {
      color: $red;
    }
  }
}
.prod-focus {
  margin-top: 100px;
  width: 100%;
  height: 700px;
  // background-color: pink;
  .swiper-container {
    .swiper_img {
      width: 100%;
      height: 700px;
    }
  }
  .detail-info {
    width: 100%;
    padding: 20px 30px;
    font-size: 30px;
    box-sizing: border-box;

    .detail-info-name {
      font-size: 40px;
      color: #333;
    }

    .detail-info-subtitle {
      padding: 10px 0;
      font-size: 28px;
      color: #999;
    }

    div {
      @include fj;
      height: 70px;
      line-height: 80px;
      padding: 10px 0;
      font-size: 32px;
      color: #999;

      .detail-info-price {
        color: $red;
        font-size: 44px;
      }
    }
  }
  .detail-content {
    width: 100%;

    .detail-gap {
      width: 100%;
      height: 20px;
      background: #eee;
    }

    ul {
      @include fj;
      width: 100%;
      margin: 20px 0;

      li {
        flex: 1;
        padding: 10px 0;
        text-align: center;
        font-size: 30px;
        border-right: 1px solid #999;
        box-sizing: border-box;

        &:last-child {
          border-right: none;
        }
      }
    }

    div.info {
      width: 100%;
      overflow: hidden;
      p {
        width: 100%;
        font-size: 40px;
        text-align: center;
      }

      ::v-deep img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .van-goods-action {
    bottom: 10px;
  }
}
</style>
